package cn.ycc1.boot3video.video;

/**
 * @author ycc
 * @date 2025/11/4
 */
public class StepByStepHlsGenerator {

    public static void generateStepByStep(String inputPath, String outputDir) {
        // 1. 先转码为中间文件（可选，用于质量控制）
        String[] intermediateFiles = {
                outputDir + "/intermediate_1080p.mp4",
                outputDir + "/intermediate_720p.mp4",
                outputDir + "/intermediate_480p.mp4"
        };

        // 2. 分别切片为HLS
        String[][] qualityConfigs = {
                {"1080p", "2000k", "1920:1080", "128k"},
                {"720p", "1000k", "1280:720", "96k"},
                {"480p", "500k", "854:480", "64k"}
        };

        for (String[] config : qualityConfigs) {
            String quality = config[0];
            String videoBitrate = config[1];
            String resolution = config[2];
            String audioBitrate = config[3];

            // 直接从源视频转码并切片（一步完成）
            String[] commands = {
                    "ffmpeg", "-i", inputPath,
                    "-c:v", "libx264",
                    "-c:a", "aac",
                    "-b:v", videoBitrate,
                    "-maxrate", String.valueOf((int)(Integer.parseInt(videoBitrate.replace("k", "")) * 1.07)) + "k",
                    "-bufsize", String.valueOf((int)(Integer.parseInt(videoBitrate.replace("k", "")) * 1.5)) + "k",
                    "-b:a", audioBitrate,
                    "-vf", "scale=" + resolution,
                    "-hls_time", "4",
                    "-hls_list_size", "0",
                    "-hls_playlist_type", "vod",
                    "-hls_segment_filename", outputDir + "/" + quality + "_%03d.ts",
                    outputDir + "/" + quality + ".m3u8"
            };

            executeFfmpegCommand(commands, quality);
        }

        // 3. 生成主播放列表
        HlsMasterPlaylistGenerator.generateMasterPlaylist(outputDir);
    }

    private static void executeFfmpegCommand(String[] commands, String quality) {
        try {
            Process process = Runtime.getRuntime().exec(commands);
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                System.out.println(quality + " processed successfully");
            } else {
                System.err.println(quality + " processing failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
